BFS(三维)Dungeon Master POJ2251
Description
You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.
Is an escape possible? If yes, how long will it take?
Input
The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size).
L is the number of levels making up the dungeon.
R and C are the number of rows and columns making up the plan of each level.
Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a ‘#’ and empty cells are represented by a ‘.’. Your starting position is indicated by ‘S’ and the exit by the letter ‘E’. There’s a single blank line after each level. Input is terminated by three zeroes for L, R and C.
Output
Each maze generates one line of output. If it is possible to reach the exit, print a line of the form
Escaped in x minute(s).
where x is replaced by the shortest time it takes to escape.
If it is not possible to escape, print the line
Trapped!
Sample Input
3 4 5
S….
.###.
.##..
###.#
#####
#####
##.##
##...
#####
#####
#.###
####E
1 3 3
S##
#E#
###
0 0 0
Sample Output
Escaped in 11 mintue(s).
Trapped!
相对于二维的BFS,仅仅是多了一维而已
另外多组输入记得数组用完初始化
做好访问标记vis数组,防超时
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 40;
int L, R, C;
char m[maxn][maxn][maxn];
bool vis[maxn][maxn][maxn];
int dx[] = {1, -1, 0, 0, 0, 0};
int dy[] = {0, 0, 1, -1, 0, 0};
int dz[] = {0, 0, 0, 0, 1, -1};
struct node
{
int x, y, z;
int step;
}start, over;
void bfs(node a, node b)
{
queue<node> q;
q.push(a);
while(!q.empty())
{
a = q.front();
q.pop();
if(a.x == b.x && a.y == b.y && a.z == b.z)
{
cout << "Escaped in " << a.step << " minute(s)." << '\n';
return ;
}
for(int i = 0; i < 6; ++i)
{
int xx = a.x + dx[i];
int yy = a.y + dy[i];
int zz = a.z + dz[i];
if(xx > L || xx <= 0 || yy > R || yy <= 0 || zz > C || zz <= 0 )
continue;
if(m[xx][yy][zz] == '#' || vis[xx][yy][zz] == 1)
continue;
vis[xx][yy][zz] = 1;///漏了这句超时
node tem;
tem.x = xx;
tem.y = yy;
tem.z = zz;
tem.step = a.step + 1;
q.push(tem);
}
}
cout << "Trapped!" << '\n';
}
int main()
{
while(~scanf("%d%d%d", &L, &R, &C) && !(L == 0 && R == 0 && C == 0) )
{
getchar();
for(int i = 1; i <= L; ++i)
{
for(int j = 1; j <= R; ++j)
{
for(int k = 1; k <= C; ++k)
{
scanf("%c", &m[i][j][k]);
if(m[i][j][k] == 'S')
{
start.x = i;
start.y = j;
start.z = k;
start.step = 0;
}
if(m[i][j][k] == 'E')
{
over.x = i;
over.y = j;
over.z = k;
}
}
getchar();
}
getchar();
}
bfs(start, over);
///错了不知怎么错的,加上这两句就过了...
memset(m, 0, sizeof(m));
memset(vis, 0, sizeof(vis));
}
return 0;
}